#include "gateway_cache.h"
#include <boost/interprocess/detail/atomic.hpp>

boost::uint32_t gateway_cache::_lock_state = 0;
gateway_cache* gateway_cache::_cache = NULL;
gateway_cache::gateway_cache(){
    _map_cache.clear();
}

gateway_cache::~gateway_cache(){}


gateway_cache* gateway_cache::get_instance()
{
    if (_cache == NULL)
    {
        while(boost::interprocess::ipcdetail::atomic_cas32(&_lock_state, 1, 0));
        if (_cache == NULL)
        {
            _cache = new gateway_cache();
        }
        boost::interprocess::ipcdetail::atomic_cas32(&_lock_state, 0, 1);
    }
    return _cache;
}

int gateway_cache::insert_client(std::string strid, gateway_client_ptr client_ptr)
{
    boost::recursive_mutex::scoped_lock lock(_rmutex);
    Map_Client::iterator it = _map_cache.find(strid);
    if (it != _map_cache.end())
    {
        it->second->close();
        _map_cache.erase(it);
    }
    //添加新的客户端
    _map_cache.insert(make_pair(strid, client_ptr));
    return 0;
}

int gateway_cache::del_client(std::string strid, std::string addr)
{
    boost::recursive_mutex::scoped_lock lock(_rmutex);
    Map_Client::iterator it = _map_cache.find(strid);
    if (it != _map_cache.end())
    {
        if (addr.compare(it->second->get_addr()) == 0)//删除之前核对ip:port是否相同,防止误删
            _map_cache.erase(it);
    }
    return 0;
}

void gateway_cache::clear()
{
    boost::recursive_mutex::scoped_lock lock(_rmutex);
    Map_Client::iterator it = _map_cache.begin();
    for (; it != _map_cache.end();)
    {
        it->second->close();
        _map_cache.erase(it++);
    }
    return;
}
